const { ccclass, property } = cc._decorator;
import { gameEvents } from "../../constants";
import { IconResourcePath } from "../bean/Config";

@ccclass
export default class resourceItem extends cc.Component {
    private icon: cc.Sprite = null; //物品图标
    private titleLabel: cc.Label = null; //物品名

    public count: number = 1; //物品刷新数量
    public itemId: string = null; //资源物品ID
    public remark: string = ""; //资源物品描述
    public title: string = ""; //资源物品名
    public lv: number = 1; //资源物品等级
    public rare: number = 1; //资源物品稀有度
    public rowId: number = null; //物品在地图上的编号
    public mapId: number = null; //地图编号

    protected onLoad() {
        this.node.on(cc.Node.EventType.TOUCH_END, this.onPickup, this);
        this.icon = this.node.getComponent(cc.Sprite);
        this.titleLabel = this.node.getChildByName("titleLabel").getComponent(cc.Label);
    }

    start() {}

    protected onDestroy() {
        this.node.off(cc.Node.EventType.TOUCH_END, this.onPickup, this);
    }

    private onPickup() {
        cc.director.emit(gameEvents.onResourcePickup.toString(), this.node);
    }

    //初始化资源
    public init(itemId: string, count: number, remark: string, lv: number, rare: number, title: string, rowId: number, mapId: number) {
        if (this.icon == null) {
            this.icon = this.node.getComponent(cc.Sprite);
        }
        if (this.titleLabel == null) {
            this.titleLabel = this.node.getChildByName("titleLabel").getComponent(cc.Label);
        }

        this.itemId = itemId;
        this.count = count;
        this.remark = remark;
        this.lv = lv;
        this.rare = rare;
        this.title = title;
        this.rowId = rowId;
        this.mapId = mapId;

        this.titleLabel.string = this.title + "x" + this.count;
        if (this.rare >= 0.5 && this.rare < 0.8) {
            this.titleLabel.node.color = this.node.color.fromHEX("#0DFF38");
        } else if (this.rare >= 0.3 && this.rare < 0.5) {
            this.titleLabel.node.color = this.node.color.fromHEX("#0F00FE");
        } else if (this.rare < 0.3) {
            this.titleLabel.node.color = this.node.color.fromHEX("#FE00EF");
        }

        let iconPath = IconResourcePath.bagItem + itemId;
        cc.resources.load(iconPath, cc.SpriteFrame, (err, obj: any) => {
            this.icon.spriteFrame = obj;
        });
    }
}
